package org.opu.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 *
 * @author yura
 */
public class TestXml {

    private String text;
    private String errorMsg;

    public TestXml(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
    
    /**
     *  Return true if text can be parsed like XML-document
     * @return true if text can be parsed like XML-document
     */
    public boolean test(){
        if (text == null){
            errorMsg = "Data can be null !";
            return false;
        }

        errorMsg = null;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            errorMsg = String.valueOf(ex);
            return false;
        }

        Document doc = null;
        try {
            doc = builder.parse(new ByteArrayInputStream(text.getBytes()));
        } catch (SAXException ex) {
            errorMsg = String.valueOf(ex);
            return false;
        } catch (IOException ex) {
            errorMsg = String.valueOf(ex);
            return false;
        }

        return true;
    }

    /**
     *  If test method return false, return error message, else null
     * @return error message if test method return false, else - null
     */
    public String getErrorMsg(){
        return errorMsg;
    }
}
